package com.ptkc.web;

import com.ptkc.constants.Page;
import com.ptkc.constants.WebResult;
import com.ptkc.data.repository.DeliverCostRepository;
import com.ptkc.utils.DatesUtil;
import com.ptkc.utils.MyUtil;
import com.ptkc.utils.NumberUtils;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.builders.PointBuilder;
import org.elasticsearch.common.geo.builders.ShapeBuilders;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.*;
import org.elasticsearch.rest.RestStatus;
import org.elasticsearch.script.Script;
import org.elasticsearch.script.ScriptType;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHitField;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.sort.ScriptSortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cglib.beans.BeanMap;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import sun.management.Agent;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Array;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author: Mr.Jiao
 * @date: 2018年12月24日
 */
@RestController
@RequestMapping(value = {"/business/","search/business/"})
public class IBusContainController {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Autowired
    private DeliverCostRepository deliverCostRepository;

    private final String[] exclude = {"activities", "busPoint", "distRangeShape" , "delivercost", "selfDistRangeShape"};

    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

    @GetMapping(value = "/contain")
    public WebResult<?> getBusinessContain(@PageableDefault Pageable pageable, HttpServletRequest request) throws IOException {
        String latStr = request.getParameter("lat");
        String lngStr = request.getParameter("lon");
        if(!NumberUtils.isRealNumber(latStr) || !NumberUtils.isRealNumber(lngStr)){
            return WebResult.fail("位置坐标错误!");
        }
        double lat = Double.valueOf(latStr);
        double lon = Double.valueOf(lngStr);
        //范围内的代理商
        Set<Integer> agents = new HashSet<>();
        //范围内的商家
        Set<Integer> busIdArrays = new HashSet<>();
        this.getContainAgentIds(lon, lat, busIdArrays, agents, request);
        if(busIdArrays.size() == 0){
            return WebResult.ok(new Page<>(0, pageable.getPageNumber(), pageable.getPageSize(), new ArrayList<>()));
        }
        String sort = request.getParameter("sort");
        String isOpening = request.getParameter("isopen");
        Map<String, Map<String, Double>> deliverCost = null;
        if(agents.size() != 0) {
            deliverCost = deliverCostRepository.getDeliverCost(agents);
        }else{
            deliverCost = new HashMap<>();
        }
        //包含活动的商家
        Set<Integer> bus_arrays = this.hasActicityBusiness(request, busIdArrays);
        if(bus_arrays.size() == 0){
            return WebResult.ok(new Page<>(0, pageable.getPageNumber(), pageable.getPageSize(), new ArrayList<>()));
        }
        //查询商家
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        BoolQueryBuilder parentQueryBuilder = QueryBuilders.boolQuery();
        parentQueryBuilder.must(QueryBuilders.termsQuery("id", bus_arrays));
        //正在营业的商家
        Date currTime1790 = MyUtil.set(MyUtil.set(System.currentTimeMillis(), 1970, 0, 1), 0, Calendar.MILLISECOND);
        String today = String.valueOf(MyUtil.getDayOfWeek(new Date()));
        if("true".equalsIgnoreCase(isOpening)) {
            Map<String, Object> openingMap = new HashMap<>();
            openingMap.put("deliverCostMap", deliverCost);
            openingMap.put("time", currTime1790.getTime());
            openingMap.put("today", today);
            parentQueryBuilder.must(QueryBuilders.scriptQuery(new Script(ScriptType.STORED, null, "runfast_new_bus_opened", openingMap)));
        }
        //开店排序
        Map<String, Object> openingMap = new HashMap<>();
        openingMap.put("deliverCostMap", deliverCost);
        openingMap.put("time", currTime1790.getTime());
        openingMap.put("today", today);
        sourceBuilder.sort(SortBuilders.scriptSort(new Script(ScriptType.STORED, null, "runfast_new_bus_opened_sort", openingMap), ScriptSortBuilder.ScriptSortType.NUMBER).order(SortOrder.DESC));
        //支持预定排序
        sourceBuilder.sort(SortBuilders.scriptSort(new Script(ScriptType.STORED, null, "runfast_new_bus_suppor_reserve_sort", openingMap), ScriptSortBuilder.ScriptSortType.NUMBER).order(SortOrder.DESC));
        //排序
        if("sales".equalsIgnoreCase(sort)){
            //销量排序
            sourceBuilder.sort("salesnum", SortOrder.DESC);
        }else if("score".equalsIgnoreCase(sort)){
            sourceBuilder.sort("scoreAvg", SortOrder.DESC);
        }else if("speed".equalsIgnoreCase(sort)){
            //速度
            Map<String, Object> paramMapSpeed = new HashMap<>();
            paramMapSpeed.put("lon", lon);
            paramMapSpeed.put("lat", lat);
            Script scriptSpeed = new Script(ScriptType.STORED, null, "runfast_new_bus_speed_sort", paramMapSpeed);
            sourceBuilder.sort(SortBuilders.scriptSort(scriptSpeed, ScriptSortBuilder.ScriptSortType.NUMBER).order(SortOrder.ASC));
        }else if("startPay".equalsIgnoreCase(sort)){
            Script script = new Script(ScriptType.STORED, null, "runfast_new_bus_startpay_sort", new HashMap<>());
            sourceBuilder.sort(SortBuilders.scriptSort(script,ScriptSortBuilder.ScriptSortType.NUMBER).order(SortOrder.ASC));
        }else if("distributionfee".equalsIgnoreCase(sort)){
            //配送费最低
            Map<String, Object> paramMapDistributionfee = new HashMap<>();
            paramMapDistributionfee.put("lon", lon);
            paramMapDistributionfee.put("lat", lat);
            paramMapDistributionfee.put("deliverCostMap", deliverCost);
            Script scriptDistributionfee = new Script(ScriptType.STORED, null, "runfast_bus_new_distributionfee_sort", paramMapDistributionfee);
            sourceBuilder.sort(SortBuilders.scriptSort(scriptDistributionfee, ScriptSortBuilder.ScriptSortType.NUMBER).order(SortOrder.ASC));
        }else if("comprehensive".equalsIgnoreCase(sort)){
            //综合排序
            sourceBuilder.sort("priority", SortOrder.DESC);
            //.sort("goldBusiness", SortOrder.DESC);
            Map<String, Object> goldMap = new HashMap<>();
            goldMap.put("currTime", System.currentTimeMillis());
            Script busScript = new Script(ScriptType.STORED, null, "runfast_goldbusiness_sort", goldMap);
            sourceBuilder.sort(SortBuilders.scriptSort(busScript, ScriptSortBuilder.ScriptSortType.NUMBER).order(SortOrder.DESC));
            sourceBuilder.sort("salesnum", SortOrder.DESC);
            sourceBuilder.sort("scoreAvg", SortOrder.DESC);
        }
        sourceBuilder.sort(SortBuilders.geoDistanceSort("busPoint", lat, lon).unit(DistanceUnit.KILOMETERS).order(SortOrder.ASC));
        sourceBuilder.sort("id", SortOrder.ASC);
        sourceBuilder.from((int)pageable.getOffset()).size(pageable.getPageSize());
        //ScriptField
        Script isOpeningScript = new Script(ScriptType.STORED, null, "runfast_new_bus_opened", openingMap);
        Map<String, Object> distanceParamMap = new HashMap<>();
        distanceParamMap.put("lat", lat);
        distanceParamMap.put("lon", lon);
        Script distanceScript = new Script(ScriptType.STORED, null, "runfast_bus_new_distance", distanceParamMap);
        //是否支持预定
        Script supporBookableScript = new Script(ScriptType.STORED, null, "runfast_new_bus_suppor_reserve_sort", openingMap);
        sourceBuilder.query(parentQueryBuilder).fetchSource(null, exclude)
                .scriptField("isOpened", isOpeningScript, true).scriptField("distance", distanceScript, true)
                .scriptField("supporBookable", supporBookableScript, true);
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices("runfast_business").types("business").source(sourceBuilder);
        System.out.println(searchRequest.source());
        SearchResponse response = this.restHighLevelClient.search(searchRequest);
        if(response.status() == RestStatus.OK){
            if(response.getHits() != null){
                List<Object> busArrays = new ArrayList<>();
                SearchHits searchHits = response.getHits();
                if(searchHits.getHits() != null){
                    SearchHit[] hits = searchHits.getHits();
                    DecimalFormat df = new DecimalFormat("#.00");
                    for(SearchHit hit : hits){
                        Map sourceMap = hit.getSourceAsMap();
                        if(sourceMap != null){
                            Map<String, SearchHitField> fieldMap = hit.getFields();
                            if(fieldMap != null && !fieldMap.isEmpty()){
                                SearchHitField isOpenedField = fieldMap.get("isOpened");
                                Boolean isOpened = null;
                                if(isOpenedField == null || isOpenedField.getValue() == null){
                                    isOpened = false;
                                }else{
                                    isOpened = "true".equalsIgnoreCase(isOpenedField.getValue().toString());
                                }
                                sourceMap.put("isOpened", isOpened);
                                SearchHitField distanceField = fieldMap.get("distance");
                                Double distance = null;
                                if(distanceField != null && distanceField.getValue() != null
                                        && NumberUtils.isNumeric(distanceField.getValue().toString())){
                                    distance = Double.valueOf(distanceField.getValue().toString());
                                }else{
                                    distance = 0.00;
                                }
                                sourceMap.put("distance", String.format("%.4f",distance));

                                Boolean suporBookable = null;
                                SearchHitField supporBookable = fieldMap.get("supporBookable");
                                if(supporBookable != null && supporBookable.getValue() != null){
                                    suporBookable = "1".equals(supporBookable.getValue().toString());
                                } else {
                                    suporBookable = false;
                                }
                                sourceMap.put("bookable", suporBookable);
                            }
                        }
                        busArrays.add(sourceMap);
                    }
                }
                return WebResult.ok(new Page<>(searchHits.getTotalHits(), pageable.getPageNumber(), pageable.getPageSize(), busArrays));
            }
        }
        return WebResult.fail("查询失败");
    }

    public void getContainAgentIds(double lon, double lat, Set<Integer> busIdArray, Set<Integer> agents, HttpServletRequest servletRequest) throws IOException {

        String isDeliver = servletRequest.getParameter("isDeliver");
        String supporSelf = servletRequest.getParameter("supporSelf");
        String goldBus = servletRequest.getParameter("goldBus");
        String newBus = servletRequest.getParameter("newBus");
        String zeorStartDelivery = servletRequest.getParameter("zeorStartDelivery");

        String mainClassId = servletRequest.getParameter("mainClassId");

        SearchRequest request = new SearchRequest();
        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder parentQuery = QueryBuilders.boolQuery();
        parentQuery.mustNot(QueryBuilders.termQuery("statusx", -1));
        //配送范围
        PointBuilder pointBuilder = ShapeBuilders.newPoint(lon,lat);
        BoolQueryBuilder selfDeliverBuilder = QueryBuilders.boolQuery();
        selfDeliverBuilder.mustNot(QueryBuilders.termQuery("isDeliver", 1));
        selfDeliverBuilder.must(QueryBuilders.geoShapeQuery("distRangeShape", pointBuilder));
        BoolQueryBuilder merchantDeliverBuilder = QueryBuilders.boolQuery();
        merchantDeliverBuilder.must(QueryBuilders.termQuery("isDeliver", 1));
        merchantDeliverBuilder.must(QueryBuilders.geoShapeQuery("selfDistRangeShape", pointBuilder));
        parentQuery.must(QueryBuilders.boolQuery().should(selfDeliverBuilder).should(merchantDeliverBuilder));
        //主营类别
        if(NumberUtils.isPositiveInteger(mainClassId)){
            parentQuery.must(QueryBuilders.termQuery("mainClassId", Integer.valueOf(mainClassId)));
        }
        //自配送
        if("true".equalsIgnoreCase(isDeliver)){
            parentQuery.must(QueryBuilders.termQuery("isDeliver", 1));
        }else if("false".equalsIgnoreCase(isDeliver)){
            //平台配送
            BoolQueryBuilder plamDeliverBuilder = QueryBuilders.boolQuery();
            plamDeliverBuilder.should(QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery("isDeliver")));
            plamDeliverBuilder.should(QueryBuilders.boolQuery().mustNot(QueryBuilders.termQuery("isDeliver", 1)));
            parentQuery.must(plamDeliverBuilder);
        }
        //支持自取
        if("true".equalsIgnoreCase(supporSelf)){
            parentQuery.must(QueryBuilders.termQuery("suportSelf", true));
        }else if("false".equalsIgnoreCase(supporSelf)){
            //不支持自取
            parentQuery.mustNot(QueryBuilders.termQuery("suportSelf", true));
        }
        //金牌商家
        Map<String, Object> goldBusMap = new HashMap<>();
        goldBusMap.put("currTime", System.currentTimeMillis());
        Script goldScript = new Script(ScriptType.STORED, null, "runfast_is_goldbusiness", goldBusMap);
        if("true".equalsIgnoreCase(goldBus)){
//            parentQuery.must(QueryBuilders.termQuery("goldBusiness", true));
            parentQuery.must(QueryBuilders.scriptQuery(goldScript));
        }else if("false".equalsIgnoreCase(goldBus)){
            //非金牌商家
//            parentQuery.mustNot(QueryBuilders.termQuery("goldBusiness", true));
            parentQuery.mustNot(QueryBuilders.scriptQuery(goldScript));
        }
        //新的商家
        if("true".equalsIgnoreCase(newBus)){
            Date date = new Date();
            parentQuery.must(QueryBuilders.rangeQuery("createTime").from(MyUtil.addTimeSpan(date, 0, -10).getTime(),true));
        }
        //0元起送
        if("true".equalsIgnoreCase(zeorStartDelivery)){
            parentQuery.must(QueryBuilders.termQuery("startPay", 0));
        }
        builder.query(parentQuery).from(0).size(10000).fetchSource(new String[]{"agentId", "id"}, null);
        request.source(builder).indices("runfast_business").types("business");
        System.out.println(request.source());
        SearchResponse response = this.restHighLevelClient.search(request);
        if(response.status()==RestStatus.OK && response.getHits() != null){
            SearchHits searchHits = response.getHits();
            if(searchHits.getHits() != null){
                for(SearchHit hit : searchHits.getHits()){
                    if(hit != null){
                        Map<String, Object> itemMap = hit.getSourceAsMap();
                        Object busIdObj = itemMap.get("id");
                        if(busIdObj != null && NumberUtils.isPositiveInteger(busIdObj.toString())){
                            busIdArray.add(Integer.valueOf(busIdObj.toString()));
                        }

                        Object agentIdObj = itemMap.get("agentId");
                        if(agentIdObj != null && NumberUtils.isPositiveInteger(agentIdObj.toString())){
                            agents.add(Integer.valueOf(agentIdObj.toString()));
                        }

                    }
                }
            }
        }
    }



    /**
     * 获取支持活动的商家
     * @param request
     * @param busArrays
     * @return
     */
    public Set<Integer> hasActicityBusiness(HttpServletRequest request, Set<Integer> busArrays) throws IOException {

        BoolQueryBuilder parentQueryBuilder = QueryBuilders.boolQuery();
        //满减优惠
        String fullReduction = request.getParameter("fullReduction");
        //折扣商品
        String discountMerchandise = request.getParameter("discountMerchandise");
        //免配送费
        String freeDistribution = request.getParameter("freeDistribution");
        //首单立减
        String firstReduction = request.getParameter("firstReduction");
        //进店领券
        String admissionTicket = request.getParameter("admissionTicket");
        //优惠商家
        String discountMerchant = request.getParameter("discountMerchant");
        //满赠活动
        String fullGiving = request.getParameter("fullGiving");

        if("true".equalsIgnoreCase(fullReduction) || "true".equalsIgnoreCase(discountMerchandise) ||
                "true".equalsIgnoreCase(freeDistribution) || "true".equalsIgnoreCase(firstReduction) ||
                "true".equalsIgnoreCase(admissionTicket) || "true".equalsIgnoreCase(discountMerchant)
                || "true".equalsIgnoreCase(fullGiving)){
//            BoolQueryBuilder nestedQuery = QueryBuilders.boolQuery();
//            if(!"true".equalsIgnoreCase(discountMerchant)){
//                if(fullReduction != null){
//                    nestedQuery.must(QueryBuilders.termQuery("target.type", 1));
//                }
//                if(discountMerchandise != null){
//                    nestedQuery.must(QueryBuilders.termsQuery("target.type", new int[]{2,4}));
//                }
//                if(freeDistribution != null){
//                    nestedQuery.must(QueryBuilders.termsQuery("target.type", new int[]{5,7}));
//                }
//                if(firstReduction != null){
//                    nestedQuery.must(QueryBuilders.termQuery("target.type", 9));
//                }
//                if(admissionTicket != null){
//                    nestedQuery.must(QueryBuilders.termQuery("target.type", 10));
//                }
//            }
//            NestedQueryBuilder nestedQueryBuilder = new NestedQueryBuilder("target", nestedQuery, ScoreMode.None);
//            parentQueryBuilder.must(nestedQueryBuilder);
//            if(!"true".equalsIgnoreCase(discountMerchant)){
                List<Integer> ptypes = new ArrayList<>();
                if("TRUE".equalsIgnoreCase(fullReduction)){
                    ptypes.add(1);
                }
                if("TRUE".equalsIgnoreCase(discountMerchandise)){
                    ptypes.add(2);
                    ptypes.add(4);
                }
                if("TRUE".equalsIgnoreCase(freeDistribution)){
                    ptypes.add(5);
                    ptypes.add(7);
                }
                if("TRUE".equalsIgnoreCase(firstReduction)){
                    ptypes.add(9);
                }
                if("TRUE".equalsIgnoreCase(admissionTicket)){
                    ptypes.add(10);
                }
                if("TRUE".equalsIgnoreCase(fullGiving)){
                    ptypes.add(3);
                }
                if(ptypes.size() > 0){
                    parentQueryBuilder.must(QueryBuilders.termsQuery("ptype", ptypes));
                }
//            }
        }else{
            return busArrays;
        }

        Date curr_time = new Date();
        Date curr_time1970 = MyUtil.set(MyUtil.set(System.currentTimeMillis(), 1970, 0, 1), 0, Calendar.MILLISECOND);
        parentQueryBuilder.must(QueryBuilders.rangeQuery("startTime").lte(curr_time.getTime())).must(QueryBuilders.rangeQuery("endTime").gte(curr_time.getTime()));

        //nested查询
        BoolQueryBuilder nestedQueryBuilder = QueryBuilders.boolQuery();
        nestedQueryBuilder.must(QueryBuilders.termsQuery("target.businessId", busArrays));
        nestedQueryBuilder.must(QueryBuilders.boolQuery().should(QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery("target.stops"))).should(QueryBuilders.termQuery("target.stops", 0)));
        nestedQueryBuilder.must(QueryBuilders.boolQuery().should(QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery("target.deleted"))).should(QueryBuilders.termQuery("target.deleted", false)));

        NestedQueryBuilder nestedBusIdQuery = QueryBuilders.nestedQuery("target", nestedQueryBuilder, ScoreMode.None);
        nestedBusIdQuery.innerHit(new InnerHitBuilder().setFrom(0).setSize(1000));
        parentQueryBuilder.must(nestedBusIdQuery);

        parentQueryBuilder.must(QueryBuilders.boolQuery().should(QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery("stops"))).should(QueryBuilders.termQuery("stops", 0)));
        parentQueryBuilder.must(QueryBuilders.boolQuery().should(QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery("deleted"))).should(QueryBuilders.termQuery("deleted", 0)));
        parentQueryBuilder.must(QueryBuilders.boolQuery().should(QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery("discard"))).should(QueryBuilders.termQuery("discard", 0)));

        //全天活动
        BoolQueryBuilder allDayBuilder = QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery("start1"))
                .mustNot(QueryBuilders.existsQuery("start2")).mustNot(QueryBuilders.existsQuery("start3"))
                .mustNot(QueryBuilders.existsQuery("end1")).mustNot(QueryBuilders.existsQuery("end2"))
                .mustNot(QueryBuilders.existsQuery("end3"));
        //指定时间活动
        BoolQueryBuilder cognizanceBuilder = QueryBuilders.boolQuery();
        cognizanceBuilder.should(QueryBuilders.boolQuery().must(QueryBuilders.rangeQuery("start1").lte(curr_time1970)).must(QueryBuilders.rangeQuery("end1").gte(curr_time1970)));
        cognizanceBuilder.should(QueryBuilders.boolQuery().must(QueryBuilders.rangeQuery("start2").lte(curr_time1970)).must(QueryBuilders.rangeQuery("end2").gte(curr_time1970)));
        cognizanceBuilder.should(QueryBuilders.boolQuery().must(QueryBuilders.rangeQuery("start3").lte(curr_time1970)).must(QueryBuilders.rangeQuery("end3").gte(curr_time1970)));
        //生效时间段
        parentQueryBuilder.must(QueryBuilders.boolQuery().should(allDayBuilder).should(cognizanceBuilder));

        int day = MyUtil.getDayOfWeek(curr_time);
        BoolQueryBuilder weekBuilders = QueryBuilders.boolQuery().should(QueryBuilders.boolQuery().mustNot(QueryBuilders.existsQuery("week")))
                .should(QueryBuilders.wildcardQuery("week", String.format("*%s*", day)));
        parentQueryBuilder.must(weekBuilders);

        SearchRequest searchRequest = new SearchRequest();
        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
        sourceBuilder.query(parentQueryBuilder).fetchSource(new String[]{"id"}, null);
        sourceBuilder.from(0).size(10000);
        searchRequest.source(sourceBuilder).indices("runfast_activity").types("activity");
        System.err.println(searchRequest.source());
        SearchResponse response = this.restHighLevelClient.search(searchRequest);
        Set<Integer> businessArrays = new HashSet<>();
        if(response.status() == RestStatus.OK){
            SearchHits searchHits = response.getHits();
            if(searchHits != null && searchHits.getHits() != null){
                SearchHit[] hits = searchHits.getHits();
                for(SearchHit hit : hits){
                    if(hit == null || hit.getInnerHits() == null){
                        continue;
                    }
                    Map<String, SearchHits> innerHits = hit.getInnerHits();
                    SearchHits searchHits1 = innerHits.get("target");
                    if(searchHits1 == null || searchHits1.getHits() == null){
                        continue;
                    }
                    SearchHit[] hits1 = searchHits1.getHits();
                    for(SearchHit hit1 : hits1){
                        if(hit1 == null){
                            continue;
                        }
                        Map searchMap = hit1.getSourceAsMap();
                        if(searchMap != null){
                            Object busIdObj = searchMap.get("businessId");
                            if(busIdObj != null && NumberUtils.isPositiveInteger(busIdObj.toString())){
                                Integer busId = Integer.valueOf(busIdObj.toString());
                                businessArrays.add(busId);
                            }
                        }
                    }
                }
            }
        }
        return businessArrays;
    }

    private Date formatUTC(String UTCStr){
        Date date = null;
        try {
            date = sdf.parse(UTCStr);
        } catch (ParseException e) {
            e.printStackTrace();
            return date;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.set(Calendar.HOUR, calendar.get(Calendar.HOUR) + 8);
        return calendar.getTime();
    }

}
